import React, {
	Component,
	Fragment
} from 'react';
import '../common/style.css';
import TodoItem from './TodoItem';
import axios from 'axios';

class TodoList extends Component {

	constructor(props) {
		super(props);
		this.state = {
			inputValue: '',
			list: []
		}

		this.handleInputChange = this.handleInputChange.bind(this);
		this.handleButtonClick = this.handleButtonClick.bind(this);
		this.handleItemDelete = this.handleItemDelete.bind(this);
	}


	render() {
		// console.log("parent render");
		return (
			<Fragment>
				<div>
					<label htmlFor={'insertArea'}>请输入内容：</label>
				  {/*input框-注释*/}
					<input 
						id = {'insertArea'}
					  className = {'input'}
						value = {this.state.inputValue} 
						onChange = {this.handleInputChange}
						ref = {(input) => {this.input = input}}
					/>
					<button
						onClick = {this.handleButtonClick}
					>提交</button>
				</div>
				{ /*列表标签-注释*/ }
				<ul ref = {(ul) => {this.ul = ul}}>
					{this.getTodoItem()}
				</ul>
			</Fragment>
		);
	};

	componentDidMount() {
		axios.get('http://localhost:8083/auth/v1/todoList')
			.then((res) => {
				// console.log(res);
				this.setState(() => ({
					list: [...res.data]
				}));
			})
			.catch(() => {
				console.log('error')
			});
	}

	getTodoItem() {
		return this.state.list.map(
			(item, index) => {
				return (
					<TodoItem 
						key={index}
						content = {item}
						index = {index}
						deleteItem = {this.handleItemDelete}
					/>
				)
			}
		)
	}

	handleItemDelete(index) {
		this.setState((prevState) => {
			const list = [...prevState.list];
			list.splice(index, 1);
			return ({
				list
			});
		});
	}

	handleButtonClick() {
		this.setState((prevState) => ({
			list: [...prevState.list, prevState.inputValue],
			inputValue: ''
		}), () => {
			// console.log(this.ul.querySelectorAll('div').length);
		});
	}

	handleInputChange(e) {
		// console.log(e.target);
		// console.log(this);
		// console.log(this.input)
		const value = e.target.value;
		this.setState(() => ({
			inputValue: value
		}));
	}

}

export default TodoList;